package com.styytech.dadabao.ui.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.TextView;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.styytech.dadabao.DadaApplication;
import com.styytech.dadabao.R;
import com.styytech.dadabao.base.BaseActivity;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.utils.Md5Utils;
import com.styytech.dadabao.utils.SpUser;
import com.styytech.dadabao.widge.gesturepassword.LocusPassWordView;

/**
 * 登录界面
 */
@ContentView(R.layout.activity_draw_pwd)
public class GesturePasswordActivity extends BaseActivity implements View.OnClickListener {

    private final static int SHAKETIME = 5;// 摇晃次数
//    private final static int ERRORTIME = 5;// 错误次数

    /*手机号*/
    @ViewInject(R.id.tv_phone_number)
    private TextView tv_phone_number;
    /*忘记密码*/
    @ViewInject(R.id.tv_forget_passwd)
    private TextView tv_forget_passwd;
    /*提示*/
    @ViewInject(R.id.tv_tips)
    private TextView tv_tips;

    private LocusPassWordView mPwdView;// 手势密码类
    private Context mContext;// 上下文
    //    private boolean isGestureSwitchOpen = true;//true：手势密码开,false:手势密码关
    private boolean isUpdateGesturePassword = false;//true：修改手势密码,false:验证手势密码
    private String userGesturePassword = null;// 手势密码
    private String setGesturePasswordTemp = null;// 设置手势密码的临时密码
    private String updateGesturePasswordTemp = null;// 修改手势密码的临时密码
    private int mode = 0;// 0：设置手势密码，1：修改手势密码：2：验证手势密码
    private int animateCount;// 记录摇晃的次数
    private int errorCount = 5;// 记录错误次数
    private int okCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getApplicationContext();
        initView();
        gesturePass();

    }

    private void initView() {
        mPwdView = (LocusPassWordView) this.findViewById(R.id.gesture_password);
        DadaApplication.addActivity(this);

        /*获取用户账号（手机号）*/
        String phone = SpUser.getUserName(mContext);
        if (phone != null) {
            phone = phone.substring(0, 3) + "****" + phone.substring(7, 11);
            tv_phone_number.setText(phone.toString());
        }
        /*获取已设置的手势密码，未设置过为null*/
        userGesturePassword = SpUser.getUserGesturePassword(mContext);
        /*如果手势密码开,则获取是否要修改手势密码*/
        isUpdateGesturePassword = getIntent().getBooleanExtra("UPDATEGESTURE", false);
        if (userGesturePassword == null) {//未设置过手势密码，进入设置
            setTopBar("设置手势密码", View.VISIBLE);
            tv_tips.setText(mContext.getString(R.string.gesture_draw_pwd));
            tv_forget_passwd.setText("跳过");
            mode = 0;
        } else if (isUpdateGesturePassword == true) {// 修改手势密码
            setTopBar("修改手势密码", View.VISIBLE);
            tv_tips.setText(mContext.getString(R.string.gesture_draw_old));
            mode = 1;

        } else if (userGesturePassword != null && !isUpdateGesturePassword) {// 验证手势密码
            setTopBar("手势密码", View.VISIBLE);
            tv_tips.setText(mContext.getString(R.string.gesture_draw_pwd));
            mode = 2;
        }

        tv_forget_passwd.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        if (tv_forget_passwd.getText().equals("跳过")) {
            CommonUtils.showToastMsg(mContext,"由于您未设置手势密码，所以手势开关自动关闭了");
            SpUser.setGestureSwitch(mContext, false);
            finish();
        } else {// 忘记手势密码
            forgetPassword();
        }
    }

    private void gesturePass() {
        mPwdView.setOnCompleteListener(new LocusPassWordView.OnCompleteListener() {
            @Override
            public void onComplete(String mPassword) {
                String mD5Pass = Md5Utils.hash(mPassword);// 密码加密

                if (mode == 0) {// 设置手势密码
                    if (setGesturePasswordTemp == null) {
                        setGesturePasswordTemp = mD5Pass;
                        tv_tips.setText(mContext.getString(R.string.gesture_ok_again));
                        mPwdView.clearPassword();
                    } else if (mD5Pass.equals(setGesturePasswordTemp)) {// 验证设置手势密码
                        mPwdView.clearPassword();
                        // 如果未设置过手势密码，则存储手势密码
                        SpUser.setUserGesturePassword(mContext, mD5Pass);
                        finish();
                    } else {
                        mPwdView.markError();
                    }
                } else if (mode == 1) {//修改手势密码
                    if (mD5Pass.equals(userGesturePassword)) {
                        if(updateGesturePasswordTemp != null){// 如果验证旧密码之后，重新设置了新密码，第二次新密码又和原密码一样提示错误
                            mPwdView.markError();
                        }else if (okCount > 0) {
                            tv_tips.setText(mContext.getString(R.string.gesture_equal_old));
                            mPwdView.markError();
                        }else{
                            okCount ++;
                            setGesturePasswordTemp = mD5Pass;
                            tv_tips.setText(mContext.getString(R.string.gesture_draw_new));
                            mPwdView.clearPassword();
                        }

                    } else if (setGesturePasswordTemp != null) {// 验证设置手势密码

                        if (updateGesturePasswordTemp == null) {
                            updateGesturePasswordTemp = mD5Pass;
                            tv_tips.setText(mContext.getString(R.string.gesture_ok_again));
                            mPwdView.clearPassword();
                        } else if (updateGesturePasswordTemp != null) {
                            if (mD5Pass.equals(updateGesturePasswordTemp)) {
                                mPwdView.clearPassword();
                                // 如果未设置过手势密码，则存储手势密码
                                SpUser.setUserGesturePassword(mContext, mD5Pass);
                                finish();
                            } else {
                                mPwdView.markError();
                            }
                        }
                    } else  {
                        puaError();
                    }

                } else if (mode == 2) {//验证手势密码
                    if (mD5Pass.equals(userGesturePassword)) {
                        startMainActivity(MainActivity.class);
                    } else {
                        puaError();
                    }
                }
            }
        });
    }

    /**
     * 启动界面
     *
     * @param cls 需要启动的界面类
     */
    private void startMainActivity(Class<?> cls) {
        Intent intent = new Intent(mContext, cls);
        startActivity(intent);
        finish();
    }


    /**
     * 控件围绕中心上下摇晃效果
     *
     * @param v 控件
     */
    private void shakeAnimation(final View v) {
        float rotate = 10;
        final RotateAnimation mra = new RotateAnimation(rotate, -rotate,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        final RotateAnimation mrb = new RotateAnimation(-rotate, rotate,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);

//        mra.setRepeatCount(-1);
        mra.setDuration(90);
        mrb.setDuration(90);

        animateCount = SHAKETIME;
        mra.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationEnd(Animation animation) {
                animateCount--;
                mra.reset();
                if (animateCount > 0) {
                    v.startAnimation(mrb);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationStart(Animation animation) {

            }

        });

        mrb.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationEnd(Animation animation) {
                mrb.reset();
                v.startAnimation(mra);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationStart(Animation animation) {

            }

        });
        v.startAnimation(mra);
    }


    /**
     * 解锁错误
     */
    private void puaError() {
        if (errorCount > 1) {
            errorCount--;
            tv_tips.setText(getResources().getString(R.string.gesture_errer_time) + errorCount + "次");
            shakeAnimation(tv_tips);
            mPwdView.clearPassword();// 清除绘制界面
        } else {
            mPwdView.clearPassword();
            forgetPassword();
        }
    }

    /**
     * 忘记手势密码
     */
    private void forgetPassword() {
        SpUser.setUserToken(mContext, null);
        SpUser.setUserGesturePassword(mContext, null);
        SpUser.setGestureSwitch(mContext, true);
        SpUser.setUserName(mContext, null);
        startMainActivity(MainActivity.class);
        finish();
    }
}
